<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-Hans">
<head><meta name="generator" content="Hexo 3.8.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">



  
  
    
    
  <script src="/lib/pace/pace.min.js?v=1.0.2"></script>
  <link href="/lib/pace/pace-theme-minimal.min.css?v=1.0.2" rel="stylesheet">







<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">






















<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/favicon-32x32-st.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-st.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-32x32-st.png?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="XSS,">





  <link rel="alternate" href="/atom.xml" title="卷柏的花期" type="application/atom+xml">






<meta name="description" content="本篇重点是介绍 XSS 攻击的特点与危害，以及目前防御 XSS 攻击的常用方法。">
<meta name="keywords" content="XSS">
<meta property="og:type" content="article">
<meta property="og:title" content="WEB安全 - 认识与防御XSS攻击">
<meta property="og:url" content="http://yoursite.com/2018/08/14/xss/index.html">
<meta property="og:site_name" content="卷柏的花期">
<meta property="og:description" content="本篇重点是介绍 XSS 攻击的特点与危害，以及目前防御 XSS 攻击的常用方法。">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="http://yoursite.com/2018/08/14/xss/xss.jpg">
<meta property="og:image" content="http://yoursite.com/2018/08/14/xss/xss-step.png">
<meta property="og:image" content="http://yoursite.com/2018/08/14/xss/jd.png">
<meta property="og:image" content="http://yoursite.com/2018/08/14/xss/zh-1.png">
<meta property="og:image" content="http://yoursite.com/2018/08/14/xss/zh-2.png">
<meta property="og:updated_time" content="2019-01-01T14:28:35.969Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="WEB安全 - 认识与防御XSS攻击">
<meta name="twitter:description" content="本篇重点是介绍 XSS 攻击的特点与危害，以及目前防御 XSS 攻击的常用方法。">
<meta name="twitter:image" content="http://yoursite.com/2018/08/14/xss/xss.jpg">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Gemini',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: false,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://yoursite.com/2018/08/14/xss/">





  <title>WEB安全 - 认识与防御XSS攻击 | 卷柏的花期</title>
  








</head>

<body itemscope="" itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband">
    <a href="https://gitee.com/Selaginella/" target="_blank" style="position:absolute;right:0;top:0;border:none"><img src="https://gitee.com/Selaginella/Selaginella/widgets/widget_1.svg" alt="Fork me on Gitee"></a>
    </div>

    <header id="header" class="header" itemscope="" itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">卷柏的花期</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">随风而动，九死还生</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br>
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-source">
          <a href="/source/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-flask"></i> <br>
            
            资源
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br>
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off" placeholder="搜索..." spellcheck="false" type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope="" itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://yoursite.com/2018/08/14/xss/">

    <span hidden itemprop="author" itemscope="" itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Selaginella">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/uploads/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope="" itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="卷柏的花期">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">WEB安全 - 认识与防御XSS攻击</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2018-08-14T00:24:00+08:00">
                2018-08-13
              </time>
            

            

            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope="" itemtype="http://schema.org/Thing">
                  <a href="/categories/WEB安全/" itemprop="url" rel="index">
                    <span itemprop="name">WEB安全</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <blockquote class="blockquote-center"><img src="/2018/08/14/xss/xss.jpg" alt="&#39;JavaScript 高级程序设计&#39;">本篇重点是介绍 <code>XSS</code> 攻击的特点与危害，以及目前防御 XSS 攻击的常用方法。 </blockquote>

<a id="more"></a>
<h2 id="什么是xss攻击？"><a href="#什么是xss攻击？" class="headerlink" title="什么是xss攻击？"></a>什么是xss攻击？</h2><p>XSS，即（Cross Site Scripting）中文名称为“跨站脚本攻击”。<br>XSS的重点不在于跨站攻击而在于脚本攻击。攻击者可以利用 web应用的漏洞或缺陷之处，向页面注入恶意的程序或代码，以达到攻击的目的。<br>通俗的来说就是我们的页面在加载并且渲染绘制的过程中，如果加载并执行了意料之外的程序或代码（脚本、样式），就可以认为是受到了 XSS攻击。</p>
<h2 id="XSS的危害"><a href="#XSS的危害" class="headerlink" title="XSS的危害"></a>XSS的危害</h2><ul>
<li>通过 <code>document.cookie</code> 盗取 cookie中的信息</li>
<li>使用 js或 css破坏页面正常的结构与样式</li>
<li>流量劫持（通过访问某段具有 <code>window.location.href</code> 定位到其他页面）</li>
<li>dos攻击：利用合理的客户端请求来占用过多的服务器资源，从而使合法用户无法得到服务器响应。并且通过携带过程的  cookie信息可以使服务端返回400开头的状态码，从而拒绝合理的请求服务。</li>
<li>利用 iframe、frame、XMLHttpRequest或上述 Flash等方式，以（被攻击）用户的身份执行一些管理动作，或执行一些一般的如发微博、加好友、发私信等操作，并且攻击者还可以利用 iframe，frame进一步的进行 CSRF 攻击。</li>
<li>控制企业数据，包括读取、篡改、添加、删除企业敏感数据的能力。</li>
</ul>
<h2 id="XSS攻击分类"><a href="#XSS攻击分类" class="headerlink" title="XSS攻击分类"></a>XSS攻击分类</h2><p>XSS 根据攻击是否持久，可以分为 “反射型XSS”与“存储型XSS”两种。<br>“反射型XSS”攻击者通过包装特定的连接，并将链接发送给实际的用户来进行攻击。<br>“反射型XSS”攻击一般是利用前端代码的漏洞或缺陷，比如使用 Eval来解析执行动态传入的数据，或者是一些被后端接受处理后再返回前端展示的 URL参数等，其操作手法很类似于钓鱼攻击。<br>“存储型XSS”攻击是通过表单提交，抓包工具，直接调用接口等形式向后端数据库注入数据。一旦被注入成功，并在输出的页面上没有做任何防范措施，那么所有访问这个页面的用户都会被攻击。<br>总的来说，“反射型XSS”是一种局部非持久的针对性攻击，而“存储型XSS”就要严重的多，它是一个全面大范围可持久型的攻击。</p>
<h2 id="xss攻击示例"><a href="#xss攻击示例" class="headerlink" title="xss攻击示例"></a>xss攻击示例</h2><h3 id="反射型攻击-前端URL参数解析"><a href="#反射型攻击-前端URL参数解析" class="headerlink" title="反射型攻击 - 前端URL参数解析"></a>反射型攻击 - 前端URL参数解析</h3><p>正常页面链接：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">http://xss-example.com/index.html?data=&#123;&#125;</span><br></pre></td></tr></table></figure></p>
<p>攻击者包装后的链接（data可能是需要Eval解析的Json数据）<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">http://xss-example.com/index.html?data=alert(documet.cookie)</span><br></pre></td></tr></table></figure></p>
<p>前端会被攻击的代码<br><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> data = <span class="built_in">eval</span>(<span class="string">'('</span>+ getUrlParams(<span class="string">'data'</span>) +<span class="string">')'</span>);</span><br></pre></td></tr></table></figure></p>
<p>PS：当然在实际情况下，攻击者是不会把攻击代码这么明显的暴漏出来，一般都会经过编码。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">http://xss-example.com/index.html?data=\u0061\u006c\u0065\u0072\u0074(1)</span><br></pre></td></tr></table></figure>
<p>如果你认为在解析 URL参数时不使用 <code>Eval</code> 便能保证安全，那就大错特错了，因为攻击者往往会主动的帮你执行 <code>eval</code>。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">http://xss-example.com/index.html?url=http://exmaple.com</span><br></pre></td></tr></table></figure>
<p>然后前端代码去解析并埋入一个 <code>&lt;a&gt;</code> 标记中。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> _href = getUrlParams(<span class="string">'url'</span>);</span><br><span class="line">$(<span class="string">'a'</span>).attr(<span class="string">'href'</span>, _href);</span><br></pre></td></tr></table></figure>
<p>但是，现在如果攻击者利用了您这个功能包装了这样的一条链接呢？</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">http://xss-example.com/index.html?url=javascript:eval(alert(document.cookie));</span><br></pre></td></tr></table></figure>
<p>编码之后：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">http://xss-example.com/index.html?url=javascript:\u0065\u0076\u0061\u006c(\u0061\u006c\u0065\u0072\u0074(document.cookie));</span><br></pre></td></tr></table></figure>
<h3 id="反射型攻击-后端URL参数解析"><a href="#反射型攻击-后端URL参数解析" class="headerlink" title="反射型攻击 - 后端URL参数解析"></a>反射型攻击 - 后端URL参数解析</h3><p>现在有这样一个链接，URL参数会被后端的程序解析并返回给前端页面。<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">http://xss-example.com/index.html?name=&quot;xiaoming&quot;;</span><br></pre></td></tr></table></figure></p>
<p>后端代码示例：<br><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">app.get(<span class="string">'index.html'</span>, <span class="function"><span class="keyword">function</span> (<span class="params">req, res</span>) </span>&#123;</span><br><span class="line">    res.send(req.query.name);</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure></p>
<p>如果现在用户访问的是这样的连接，有会怎么样呢？<br><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">http:<span class="comment">//xss-example.com/index.html?name=&lt;script&gt;alert(document.cookie)&lt;/script&gt;</span></span><br></pre></td></tr></table></figure></p>
<p>此时一个脚本标记就会被后端代码重新下发给前端，然后前端将其加入页面中，便会触发攻击行为。<br>当然，实际中并没有这么可怕，因为 web程序本身就已经很好的进行了阻拦过滤，但是经过我的实际测试发现 Firefox与老版本的IE依然有这些问题，只有 Chrome 与新版本的IE进行了阻止。<br>如果你想再Chrome与新版本的IE浏览器中看到实际可产生的效果，可以通过设置 HTTP 的 Header头来关闭浏览器自动阻拦与过滤XSS功能。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">app.get(<span class="string">'index.html'</span>, <span class="function"><span class="keyword">function</span> (<span class="params">req, res</span>) </span>&#123;</span><br><span class="line">    res.set(<span class="string">'X-XSS-Protection'</span>, <span class="number">0</span>); <span class="comment">//此处是关键</span></span><br><span class="line">    res.send(req.query.name);</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>
<h3 id="注入型攻击-留言评论"><a href="#注入型攻击-留言评论" class="headerlink" title="注入型攻击 - 留言评论"></a>注入型攻击 - 留言评论</h3><p>注入型攻击常见的地方就是留言评论或者是含有表单提交的地方。<br>例如下面我们就以要给留言评论为例子来说明注入型攻击：</p>
<p>首先，攻击者向一个textarea输入以下内容：<br><figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">script</span>&gt;</span><span class="javascript">alert(<span class="built_in">document</span>.cookie)</span><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br></pre></td></tr></table></figure></p>
<p>然后，前端调用 <code>ajax</code> 向后端传值<br><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">$(<span class="string">'.send'</span>).click(<span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">    $.post(<span class="string">'message.htm'</span>,&#123;<span class="string">'msg'</span>:$(<span class="string">'textarea'</span>).val()&#125;,<span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;&#125;);</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure></p>
<p>接着，后端接收值写入数据库，同时又返回给前端展示。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">app.post(<span class="string">'message.htm'</span>,<span class="function"><span class="keyword">function</span>(<span class="params">req,res,next</span>)</span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//写入数据库</span></span><br><span class="line">    <span class="comment">//...</span></span><br><span class="line">    <span class="comment">//响应前端</span></span><br><span class="line">     res.json(&#123;</span><br><span class="line">        test: req.body.msg</span><br><span class="line">     &#125;)</span><br><span class="line"></span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>
<p>最终当前端原样展示之前输入的攻击代码时，页面便发生了存储型攻击。</p>
<p>不论是反射型攻击还是存储型，攻击者总需要找到两个要点，即“输入点”与”输出点”，也只有这两者都满足，XSS攻击才会生效。“输入点”用于向 web页面注入所需的攻击代码，而“输出点”就是攻击代码被执行的地方。</p>
<p>大致上，攻击者进行XSS攻击要经过以下几个步骤：</p>
<p><img src="/2018/08/14/xss/xss-step.png" alt=""></p>
<p>首先是分析程序寻找漏洞，然后构建攻击代码，比如上面作为留言内容的 <code>script</code> 标签，实际上可以执行前端JS代码，远程加载JS脚本CSS样式文件的 HTML标签也非常多，比如：<br><figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">&lt;!--当图片不存在时，必然触发 onerror事件--&gt;</span> </span><br><span class="line"><span class="tag">&lt;<span class="name">img</span> <span class="attr">src</span>=<span class="string">"null"</span> <span class="attr">onerror</span>=<span class="string">'alert(document.cookie)'</span> /&gt;</span> </span><br><span class="line"></span><br><span class="line"><span class="comment">&lt;!--加载远程CSS文件，破坏当前页面的样式--&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">link</span> <span class="attr">href</span>=<span class="string">"test.css"</span>&gt;</span> </span><br><span class="line"></span><br><span class="line"><span class="comment">&lt;!--点击的时候--&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">a</span> <span class="attr">onclick</span>=<span class="string">"alert(document.cookie)"</span> <span class="attr">onmouseover</span> <span class="attr">onmouseout</span>&gt;</span><span class="tag">&lt;/<span class="name">a</span>&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="comment">&lt;!--鼠标移动的时候--&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">div</span> <span class="attr">onmouseover</span>=<span class="string">‘do</span> <span class="attr">something</span> <span class="attr">here</span>’&gt;</span> </span><br><span class="line"></span><br><span class="line"><span class="comment">&lt;!--破坏页面样式--&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">style</span>&gt;</span><span class="undefined">*&#123;font-size:100px&#125;</span><span class="tag">&lt;/<span class="name">style</span>&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="comment">&lt;!--利用IE7-的 css expression表达式的行为。--&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">div</span> <span class="attr">style</span>=<span class="string">"width:expression(alert('XSS'))"</span>&gt;</span></span><br></pre></td></tr></table></figure></p>
<p>当代码注入成功后，攻击者往往就需要去寻找所注入代码的输出点，例如百度网盘之前就有一个修改昵称的 XSS漏洞，虽然前端设置了字符长度为10个字符，但是攻击者通过使用抓包工具构建了一个 <code>&lt;script&gt; document.cookie &lt;/script&gt;</code> 的执行脚本，并成功的注入到了数据库，后面测试发现，最终攻击的输出位置处于用户分享资源给其它好友时，展开好友列表的时刻。</p>
<h2 id="如何规避xss攻击？"><a href="#如何规避xss攻击？" class="headerlink" title="如何规避xss攻击？"></a>如何规避xss攻击？</h2><p>实际上简单的通过正则判断 script、link、style、img 等HTML标记并不可取，因为，首先输入点的情况变化多样，很难把所有的 html标记的特性都考虑进来，其次对html标记的限制，也会让产品的可用性大大降低（比如有些特殊的关键字会被程序阻止，使得用户使用非常不便），最后这种判断本身也不安全，比如攻击者会在关键字中插入空格、制表符以及其它HTML实体编码来躲避侦测。</p>
<p>既然我们前面说到攻击必须有两个要点：“输入点”，“输出点”，所以防御的时候，我们只要做好这两个点的控制，就基本上可以万无一失！</p>
<ul>
<li>对输入内容的特定字符进行编码，例如表示 html标记的 &lt; &gt; 等符号。</li>
<li>对重要的 cookie设置 httpOnly, 防止客户端通过<code>document.cookie</code>读取 cookie，此 HTTP头由服务端设置。</li>
<li>将不可信的值输出 URL参数之前，进行  URLEncode操作，而对于从 URL参数中获取值一定要进行格式检测（比如你需要的时URL，就判读是否满足URL格式）。</li>
<li>不要使用 Eval来解析并运行不确定的数据或代码，对于 JSON解析请使用 <code>JSON.parse()</code> 方法。</li>
<li>后端接口也应该要做到关键字符过滤的问题。</li>
</ul>
<p>就目前而言，应对XSS攻击的主要手段还是编码与过滤两种，编码用于将特殊的符号 “&lt;、&gt;、&amp;、’、””进行转义，而过滤则是阻止特定的标记、属性、事件。<br>如果你不愿意为了严格的安全而限制产品本身的灵活，那么我更建议采用“编码”的方案。</p>
<p>首先看下京东的搜索功能：</p>
<p><img src="/2018/08/14/xss/jd.png" alt=""></p>
<p>接着，再看下知乎提交评论时接口的数据：</p>
<p><img src="/2018/08/14/xss/zh-1.png" alt=""></p>
<p>最后，我们再看下知乎时如何展示提交后的评论：</p>
<p><img src="/2018/08/14/xss/zh-2.png" alt=""></p>
<p>实际上实现上述的编码功能非常简单，我们可以对照 <a href="http://www.w3school.com.cn/html/html_entities.asp" target="_blank" rel="noopener">HTML实体编码表</a> 来进行正则匹配替换。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">encode</span>(<span class="params">str</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (!str || str.length === <span class="number">0</span>) <span class="keyword">return</span> <span class="string">''</span>;</span><br><span class="line">    str = str.replace(<span class="regexp">/&gt;/gm</span>, <span class="string">'&amp;gt;'</span>);</span><br><span class="line">    str = str.replace(<span class="regexp">/&lt;/gm</span>, <span class="string">'&amp;lt;'</span>);</span><br><span class="line">    str = str.replace(<span class="regexp">/"/gm</span>, <span class="string">'&amp;quot;'</span>);</span><br><span class="line">    str = str.replace(<span class="regexp">/'/gm</span>, <span class="string">'&amp;apos;'</span>);</span><br><span class="line">    <span class="keyword">return</span> str;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>当然在实际应用中很难避免自己写的匹配规则就能万无一失，并且XSS攻击又一直是在变化的过程中，因此个人更推荐使用第三方专门防御XSS攻击的库。<br>前面都是针对输入点的防御说明，在输出的情况下，前端开发人员应当要对自己采用的输出方法与输出方式要有一定的了解：</p>
<p><strong>原生JS中</strong></p>
<table>
<thead>
<tr>
<th style="text-align:left">方法</th>
<th style="text-align:left">说明</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align:left">innerHTML</td>
<td style="text-align:left">安全，但是IE8下危险（IE8支持可见的含有defers属性的script标记，例如：<code>_&lt;script src=&quot;example.js&quot; defer&gt;&lt;/script&gt;</code>）</td>
</tr>
<tr>
<td style="text-align:left">appendChild, insertBefored等</td>
<td style="text-align:left">危险</td>
</tr>
<tr>
<td style="text-align:left">innerText</td>
<td style="text-align:left">安全</td>
</tr>
</tbody>
</table>
<p><strong>Jquery中</strong></p>
<table>
<thead>
<tr>
<th style="text-align:left">方法</th>
<th style="text-align:left">说明</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align:left">html()</td>
<td style="text-align:left">危险</td>
</tr>
<tr>
<td style="text-align:left">before,after,append等</td>
<td style="text-align:left">危险</td>
</tr>
<tr>
<td style="text-align:left">text()</td>
<td style="text-align:left">安全</td>
</tr>
</tbody>
</table>
<p><strong>EJS模版</strong></p>
<table>
<thead>
<tr>
<th style="text-align:left">输出格式</th>
<th style="text-align:left">说明</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align:left">&lt;%= &gt;</td>
<td style="text-align:left">危险，非转义的HTML输出</td>
</tr>
<tr>
<td style="text-align:left">&lt;%- &gt;</td>
<td style="text-align:left">安全，转义的HTML输出</td>
</tr>
</tbody>
</table>
<h2 id="总结"><a href="#总结" class="headerlink" title="总结"></a>总结</h2><p>首先我们了解了 XSS的定义，XSS即跨站点脚本攻击，只要浏览器加载，解析，执行了意料之外的JS，CSS等都可以被认为是受到了 XSS攻击，而 XSS攻击的分类主要有“反射型”与“存储型”两种。<br>“反射型”攻击者通过包装改造URL参数，然后利用前端代码的缺陷或漏洞来攻击，它更偏向与前端层面，并且在实际攻击中攻击者会根据 <a href="http://www.w3school.com.cn/html/html_entities.asp" target="_blank" rel="noopener">HTML实体编码</a>、<a href="http://www.w3school.com.cn/tags/html_ref_urlencode.html" target="_blank" rel="noopener">URL编码</a>、uniocde编码等进行编码然后欺骗用户点击访问。而“存储型”攻击者则会通过抓包工具或者是直接调用接口的方式想尽一切办法来向后端数据库注入数据。<br>XSS攻击有两个要点，一个是“输入点”，针对输入点我们可以对关键的特殊的字符进行编码，而在“输出点”我们要对自己采用的输出方式以及方法要有一定的安全风险认知。</p>
<blockquote class="blockquote_red">【參考資料】<br><a href="https://www.owasp.org/index.php/DOM_based_XSS_Prevention_Cheat_Sheet" target="_blank" rel="noopener">https://www.owasp.org/index.php/DOM_based_XSS_Prevention_Cheat_Sheet</a> （查看更多XSS攻击案例）<br></blockquote>

<hr>

      
    </div>
    
    
    

    

    
      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
  <div>坚持原创技术分享，您的支持将鼓励我继续创作！</div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>打赏</span>
  </button>
  <div id="QR" style="display: none;">

    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="/images/wx.jpg" alt="Selaginella 微信支付">
        <p>微信支付</p>
      </div>
    

    
      <div id="alipay" style="display: inline-block">
        <img id="alipay_qr" src="/images/alipay.jpg" alt="Selaginella 支付宝">
        <p>支付宝</p>
      </div>
    

    

  </div>
</div>

      </div>
    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/XSS/" rel="tag"># XSS</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2018/07/22/webpack-require-outline/" rel="next" title="webpack - require 概要">
                <i class="fa fa-chevron-left"></i> webpack - require 概要
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2019/04/01/professional-javascript-chapter-5-Object/" rel="prev" title="《JavaScript 高级程序设计》第五章：Object">
                《JavaScript 高级程序设计》第五章：Object <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  
    <div class="comments" id="comments">
      <div id="lv-container" data-id="city" data-uid="MTAyMC80MTkxNC8xODQ2MA"></div>
    </div>

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope="" itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image" src="/uploads/avatar.jpg" alt="Selaginella">
            
              <p class="site-author-name" itemprop="name">Selaginella</p>
              <p class="site-description motion-element" itemprop="description">知识在于积累，努力必有收获</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/">
              
                  <span class="site-state-item-count">18</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                
                  <span class="site-state-item-count">5</span>
                  <span class="site-state-item-name">分类</span>
                
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                
                  <span class="site-state-item-count">6</span>
                  <span class="site-state-item-name">标签</span>
                
              </div>
            

          </nav>

          
            <div class="feed-link motion-element">
              <a href="/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          
            <div class="links-of-author motion-element">
                
                  <span class="links-of-author-item">
                    <a href="https://github.com/shenguotao2015" target="_blank" title="gitHub">
                      
                        <i class="fa fa-fw fa-github"></i></a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://gitee.com/Selaginella" target="_blank" title="码云">
                      
                        <i class="fa fa-fw fa-telegram"></i></a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="http://www.cnblogs.com/HCJJ/" target="_blank" title="博客园">
                      
                        <i class="fa fa-fw fa-rss-square"></i></a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="mailto:sgt_ah@163.com" target="_blank" title="Email">
                      
                        <i class="fa fa-fw fa-envelope"></i></a>
                  </span>
                
            </div>
          

          
          

          
          

          
        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#什么是xss攻击？"><span class="nav-number">1.</span> <span class="nav-text">什么是xss攻击？</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#XSS的危害"><span class="nav-number">2.</span> <span class="nav-text">XSS的危害</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#XSS攻击分类"><span class="nav-number">3.</span> <span class="nav-text">XSS攻击分类</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#xss攻击示例"><span class="nav-number">4.</span> <span class="nav-text">xss攻击示例</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#反射型攻击-前端URL参数解析"><span class="nav-number">4.1.</span> <span class="nav-text">反射型攻击 - 前端URL参数解析</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#反射型攻击-后端URL参数解析"><span class="nav-number">4.2.</span> <span class="nav-text">反射型攻击 - 后端URL参数解析</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#注入型攻击-留言评论"><span class="nav-number">4.3.</span> <span class="nav-text">注入型攻击 - 留言评论</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#如何规避xss攻击？"><span class="nav-number">5.</span> <span class="nav-text">如何规避xss攻击？</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#总结"><span class="nav-number">6.</span> <span class="nav-text">总结</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; 2018 &mdash; <span itemprop="copyrightYear">2019</span>
  <span class="with-love">
    <i class="fa fa-snowflake-o"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Selaginella<span class="with-love"><i class="fa fa-heart"></i></span>Hexo 强力驱动</span>

  
</div>









        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>




















  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  
    <script type="text/javascript">
      (function(d, s) {
        var j, e = d.getElementsByTagName(s)[0];
        if (typeof LivereTower === 'function') { return; }
        j = d.createElement(s);
        j.src = 'https://cdn-city.livere.com/js/embed.dist.js';
        j.async = true;
        e.parentNode.insertBefore(j, e);
      })(document, 'script');
    </script>
  












  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  
  

  

  

  

</body>
</html>
